package com.xzx.shop_front_api.controller;

import com.xzx.shop_front_api.entity.*;
import com.xzx.shop_front_api.service.*;
import com.xzx.shop_front_api.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.IdcardUtil;

@RestController
@RequestMapping("api/members")
public class MemberController {
    @Autowired
    private MembersService membersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Members members;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private IdCardService idCardService;
    @Autowired
    private IdCard idCard;
    @Autowired
    private SettingService settingService;
    @Autowired
    private Setting setting;
    @Autowired
    private District district;

    @PostMapping("register")
    public JsonResult register(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //重复性验证
        Members membersInfo = membersService.getMembersByUsername(mobile);
        if (membersInfo != null) {
            return JsonResult.failed("该手机号码已经使用，请更换.");
        }
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        members.setMobile(mobile);
        members.setUsername(mobile);
        members.setRegisteredTime(Tool.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        System.out.println(members);
        int result = membersService.insertMembers(members);
        if (result == 0) {
            return JsonResult.failed("注册失败");
        }
        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        return JsonResult.success("注册成功", null);
    }

    //获取短信验证码
    @PostMapping("get_sms_code")
    public JsonResult getSMSCode(@RequestParam("mobile") String mobile) {
        //验证手机号格式
        if (mobile == null || mobile.trim().isEmpty() || !Tool.isMobile(mobile)) {
            return JsonResult.failed("请输入正确格式的手机号码");
        }
        //生成4位数字随机验证码
        long randomNum = Tool.generateRandomNumber(4);
        //String message = "【上海星知心教育科技】您的验证码是"+randomNum+",1分钟内有效。若非本人操作请忽略此消息";
        //调用短信接口
        //SMSUtils.sendSms(mobile, message);
        //存储到redis
        stringRedisTemplate.opsForValue().set(mobile, String.valueOf(randomNum), 60 * 60, TimeUnit.SECONDS);
        return JsonResult.success("获取成功", randomNum);
    }


    @PostMapping("login")
    public JsonResult login(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        Members memberInfo = membersService.getMembersByUsername(mobile);
        if (memberInfo == null) {
            return JsonResult.failed("登录失败");
        }

        //删除缓存验证码
        stringRedisTemplate.delete(mobile);
        HashMap<String, Object> mapMemberInfo = new HashMap<>();
        mapMemberInfo.put("id", memberInfo.getId());
        mapMemberInfo.put("username", memberInfo.getUsername());
        mapMemberInfo.put("mobile", memberInfo.getMobile());
        return JsonResult.success("登录成功", mapMemberInfo);
    }

    @PostMapping("update_password")
    public JsonResult updatePassword(@RequestParam("mobile") String mobile,
                                     @RequestParam("code") String code,
                                     @RequestParam("password") String password,
                                     @RequestParam("confirm_password") String confirmPassword
    ) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码.");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)) {
            return JsonResult.failed("输入密码格式不正确.");
        }

        if (!password.equals(confirmPassword)) {
            return JsonResult.failed("两次输入密码不一致.");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updatePassword(mobile, safePassword);
        if (result == 0) {
            return JsonResult.failed("设置成功");
        }

        //删除缓存验证码
        //stringRedisTemplate.delete(mobile);
        return JsonResult.success("设置成功", null);
    }


    @PostMapping("update_pay_password")
    public JsonResult updatePayPassword(@RequestParam("id") int id,
                                        @RequestParam("password") String password,
                                        @RequestParam("confirm_password") String confirmPassword
    ) {

        if (password == null || password.trim().isEmpty()) {
            return JsonResult.failed("请输入密码.");
        }
        //验证密码格式
        if (!Tool.isValidPassword(password)) {
            return JsonResult.failed("输入密码格式不正确.");
        }

        if (!password.equals(confirmPassword)) {
            return JsonResult.failed("两次输入密码不一致.");
        }
        String safePassword = Md5Utils.encrypt(password);
        int result = membersService.updatePayPassword(id, safePassword);
        if (result == 0) {
            return JsonResult.failed("设置成功");
        }
        return JsonResult.success("设置成功", null);
    }

    @PostMapping("check_mobile")
    public JsonResult checkMobile(@RequestParam("id") int id, @RequestParam("mobile") String mobile) {

        Members memberInfo = membersService.getMembersById(id);
        if (memberInfo == null) {
            return JsonResult.failed("该用户不存在");
        }
        if (!memberInfo.getMobile().equals(mobile)) {
            return JsonResult.failed("原手机号码输入错误");
        }

        //生成4位数字随机验证码
        long randomNum = Tool.generateRandomNumber(4);
        //String message = "【上海星知心教育科技】您的验证码是"+randomNum+",1分钟内有效。若非本人操作请忽略此消息";
        //调用短信接口
        //SMSUtils.sendSms(mobile, message);
        //存储到redis
        stringRedisTemplate.opsForValue().set(mobile, String.valueOf(randomNum), 60 * 60, TimeUnit.SECONDS);
        return JsonResult.success("获取成功", randomNum);
    }

    @PostMapping("check_code")
    public JsonResult checkCode(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }
        //stringRedisTemplate.delete(mobile);
        return JsonResult.success("验证通过", null);
    }

    @PostMapping("update_mobile")
    public JsonResult updateMobile(@RequestParam("id") int id,
                                   @RequestParam("mobile") String mobile,
                                   @RequestParam("code") String code
    ) {

        //验证手机号格式
        if (mobile == null || mobile.trim().isEmpty() || !Tool.isMobile(mobile)) {
            return JsonResult.failed("请输入正确格式的手机号码");
        }

        //短信验证码验证
        String smsCode = stringRedisTemplate.opsForValue().get(mobile);
        if (smsCode == null || !smsCode.equals(code)) {
            return JsonResult.failed("验证码输入错误.");
        }

        //验证手机号重复
        Members membersInfo = membersService.getMembersByMobile(mobile);
        if (membersInfo != null && id != membersInfo.getId()) {
            return JsonResult.failed("该手机号已经占用，请更换.");
        }
        int result = membersService.updateMobile(id, mobile);
        if (result == 0) {
            return JsonResult.failed("设置失败");
        }
        return JsonResult.success("设置成功", null);
    }

    //我的信息
    @GetMapping("my")
    public JsonResult my(@RequestParam("id") int id) {
        Members memberInfo = membersService.getMembersById(id);
        System.out.println(memberInfo);
        HashMap<String, Object> mapMemberInfo = new HashMap<>();
        mapMemberInfo.put("id", memberInfo.getId());
        mapMemberInfo.put("username", memberInfo.getUsername());
        mapMemberInfo.put("mobile", memberInfo.getMobile());
        String genderDesc = "保密";
        if (memberInfo.getGender() == 1) {
            genderDesc = "帅哥";
        } else if (memberInfo.getGender() == 0) {
            genderDesc = "美眉";
        }
        mapMemberInfo.put("gender", genderDesc);
        mapMemberInfo.put("birthday", memberInfo.getBirthday());
        mapMemberInfo.put("nickname", memberInfo.getNickname());
        mapMemberInfo.put("logo", memberInfo.getLogo());
        mapMemberInfo.put("is_auth", memberInfo.getIsAuth());
        return JsonResult.success("获取成功", mapMemberInfo);
    }

    //修改个人信息
    @PostMapping("update_myinfo")
    public JsonResult updateMyInfo(@RequestParam("id") int id,
                                   @RequestParam("username") String username,
                                   @RequestParam("nickname") String nickname,
                                   @RequestParam(value = "gender", defaultValue = "2") String gender,
                                   @RequestParam("birthday") String birthday
    ) {
        //用户名重复性验证
        Members membersInfo = membersService.getMembersByUsername(username);
        if (membersInfo != null && id != membersInfo.getId()) {
            return JsonResult.failed("该用户名已经使用，请更换.");
        }
        int result = membersService.updateMyInfo(id, username, nickname, Integer.parseInt(gender), birthday);
        if (result == 0) {
            return JsonResult.failed("更新失败");
        }
        return JsonResult.success("更新成功", null);
    }

    @PostMapping("upload_logo")
    public JsonResult uploadLogo(@RequestParam("id") int id,
                                 @RequestParam("logo") MultipartFile logo) throws IOException {
        //限制文件必选
        if (logo == null || logo.isEmpty()) {
            return JsonResult.failed("请选择上传的图片");
        }
        //验证图片格式
        //获取扩展名
        String extName = ImageUtils.getExtName(logo.getContentType());
        if (!ImageUtils.isAllowedExtName(extName)) {
            return JsonResult.failed("请上传png,jpeg,jpg格式图片");
        }
        //验证图片大小
        if (!ImageUtils.isAllowedImageSize(logo.getSize())) {
            return JsonResult.failed("图片大小不能超过2M");
        }
        //重新命名文件
        String newLogoName = "logo_" + Tool.getCurrentTime() + "." + extName;

        //logo.transferTo(new File("D:/images", newLogoName));
        //上传到七牛云存储
        try {
            String qiniuLogoUrl = qiniuService.uploadFile(logo);
            //更新头像
            int upResult = membersService.updateLogo(id, qiniuLogoUrl);
            if (upResult == 0) {
                JsonResult.failed("更新失败");
            }
            return JsonResult.success("更新成功", qiniuLogoUrl);
        } catch (Exception e) {
            return JsonResult.failed(e.getMessage());
        }
        //return JsonResult.success("ok",null);
    }

    //身份证实名认证-身份证上传
    @PostMapping("id_card_upload")
    public JsonResult idCardUpload(@RequestParam("id") int id,
                                   @RequestParam("real_name") String realName,
                                   @RequestParam("idcard_number") String idCardNumber,
                                   @RequestParam("card_image") MultipartFile[] cardImage) throws IOException {
        //限制文件必选
        if (cardImage == null || cardImage.length == 0) {
            return JsonResult.failed("请选择上传的图片");
        }
        //多图接收
        HashMap<String, Object> mapCardImageInfo = new HashMap<>();
        int i = 0;
        for (MultipartFile image : cardImage) {
            //验证图片格式
            //获取扩展名
            String extName = ImageUtils.getExtName(image.getContentType());
            if (!ImageUtils.isAllowedExtName(extName)) {
                return JsonResult.failed("请上传png,jpeg,jpg格式图片");
            }
            //验证图片大小
            if (!ImageUtils.isAllowedImageSize(image.getSize())) {
                return JsonResult.failed("图片大小不能超过2M");
            }
            //上传到七牛云存储
            try {
                String qiniuLogoUrl = qiniuService.uploadFile(image);
                mapCardImageInfo.put("cardimage_" + i, qiniuLogoUrl);
            } catch (Exception e) {
                return JsonResult.failed(e.getMessage());
            }
            i++;
        }
        return JsonResult.success("ok", mapCardImageInfo);
    }


    //身份证实名认证-提交
    @PostMapping("auth")
    public JsonResult auth(@RequestParam("id") int id,
                           @RequestParam("real_name") String realName,
                           @RequestParam("idcard_number") String idCardNumber,
                           @RequestParam("id_card_image_back") String idCardImageBack,
                           @RequestParam("id_card_image_front") String idCardImageFront
    ) throws IOException {
        //真实姓名验证
        if (realName.isEmpty()) {
            return JsonResult.failed("真实姓名不能为空");
        }
        //身份证号码验证 18位以上，以X或数字为结尾
        if (!Tool.isValidIdCard(idCardNumber)) {
            return JsonResult.failed("身份证号码格式不对.");

        }
        idCard.setMemberId(id);
        idCard.setRealName(realName);
        idCard.setIdCardImageBack(idCardImageBack);
        idCard.setIdCardImageFront(idCardImageFront);
        idCard.setIdCardNumber(idCardNumber);
        int result = idCardService.insertIdCard(idCard);
        if (result == 0) {
            return JsonResult.failed("认证失败.");
        }
        //更新会员标识
        membersService.updateIsAuth(id, 1);
        return JsonResult.success("认证成功", null);
    }

    //设置通知
    @PostMapping("set")
    public JsonResult set(@RequestParam("id") int id,
                          @RequestParam("system_notice") int systemNotice,
                          @RequestParam("activity_notice") int activityNotice,
                          @RequestParam("shake_set") int shakeSet
    ) {

        setting.setMemberId(id);
        setting.setSystemNotice(systemNotice);
        setting.setActivityNotice(activityNotice);
        setting.setShakeSet(shakeSet);

        HashMap<String, Object> mapSettingInfo = new HashMap<>();
        mapSettingInfo.put("system_notice", systemNotice);
        mapSettingInfo.put("activity_notice", activityNotice);
        mapSettingInfo.put("shake_set", shakeSet);

        //查询
        Setting settingInfo = settingService.getSettingByMemberId(id);
        if (settingInfo == null) {

            int result = settingService.insertSetting(setting);
            if (result == 0) {
                return JsonResult.failed("设置失败");
            }
            return JsonResult.success("设置成功", mapSettingInfo);
        }
        int updateResult = settingService.updateSetting(setting);

        if (updateResult == 0) {
            return JsonResult.failed("设置失败");
        }
        return JsonResult.success("设置成功", mapSettingInfo);
    }

    @GetMapping("district")
    public JsonResult district(@RequestParam("pid") int pid) {
        List<District> districtInfo = membersService.getDistrictBypId(pid);
        return JsonResult.success("获取成功", districtInfo);
    }


    //新增收件地址
    @PostMapping("add_address")
    public JsonResult addAddress(@RequestBody Address address) {
        if (address.getRecipienter().isEmpty()) {
            return JsonResult.failed("收件人不能为空");

        }
        if (address.getPhone().isEmpty()) {
            return JsonResult.failed("收件人联系方式不能为空");
        }
        System.out.println(address);
        if (address.getAreaId() == 0) {
            return JsonResult.failed("省市区必选");
        }
        //如果是默认地址
        if (address.getIsDefaulted() == 1) {
            membersService.updateDefaultedAddress(address.getMemberId(), 0);
        }
        int result = membersService.insertAddress(address);
        if (result == 0) {
            return JsonResult.failed("添加失败");
        }

        return JsonResult.success("添加成功", null);
    }

    //收件地址列表接口
    @GetMapping("address_list")
    public JsonResult addressList(@RequestParam("member_id") int member_id) {
        Members addressInfo = membersService.getMembersAddressListByMemberId(member_id);
        for (Address address : addressInfo.getAddressList()) {
            int provinceId = address.getProvinceId();
            int cityId = address.getCityId();
            int areaId = address.getAreaId();
            //获取省份名称
            District provinceInfo = membersService.getDistrictById(provinceId);
            String provinceName = provinceInfo.getName();
            //获取城市名
            District cityInfo = membersService.getDistrictById(cityId);
            String cityName = cityInfo.getName();
            //获取区县名
            District areaInfo = membersService.getDistrictById(areaId);
            String areaName = areaInfo.getName();
            address.setAddress(provinceName+cityName+areaName+address.getAddress());
        }
        return JsonResult.success("获取成功", addressInfo);

    }

    //收件地址删除
    @GetMapping("delete_address")
    public JsonResult deleteAddress(@RequestParam("id") int id) {
        //默认地址不能删除
        Address addressInfo = membersService.getAddressById(id);
        if (addressInfo == null) {
            return JsonResult.failed("删除失败，该收件地址不存在");
        }
        if (addressInfo.getIsDefaulted() == 1) {
            return JsonResult.failed("添加失败,默认地址不能删除");
        }
        int result = membersService.deleteAddressById(id);
        if (result == 0) {
            return JsonResult.failed("删除失败");
        }
        return JsonResult.success("删除成功", null);
    }

    //收件地址详情接口
    @GetMapping("address_details")
    public JsonResult addressDetails(@RequestParam("id") int id) {
        //默认地址不能删除
        Address addressInfo = membersService.getAddressById(id);
        if (addressInfo == null) {
            return JsonResult.failed("该收件地址不存在");
        }
        return JsonResult.success("查询成功", addressInfo);
    }


}
